var zTreeMenu;
var menuRoot={ id:0, parent_id:null, name:"导航菜单", open:true,nocheck:true};
var ztreeSeting = {
			view: { showLine : false },
			callback:{
			},
			data: {
				key:{
					name:"name",//节点名称的属性名称
					checked:"checked"
				},
				simpleData: {
					enable: true,
					idKey: "id",
					pIdKey: "parent_id",
					rootPId: null
				}
			},
			check: {
				enable: true,
				nocheckInherit: false
			},

};
	var comboboxDatas ;//=[{'id':'enabled','text':'启用'},{'id':'disable','text':'禁用'}]
	var dg;
	var moduleid="sys_role";
	var resultObject=$.parseJSON($.ajax({
		type: "post",
		contentType:"application/json",
		async:false,
		url: "/authenticated/grid/column/"+moduleid,
		data:null,
		dataType:"json",
		success: function(result){
			
		},
		error: function(){
			
		}
	}).responseText);
	
	if(resultObject.success){
		comboboxDatas=resultObject.data;
	}else{
		alert(resultObject.message);
	}
	
	var columns=[[
	              {field:'checkbox',checkbox:true},
	              {field:'id',title:'ID'},
	              {field:'role_name',title:'角色名称',sortable:true,editor:{
						type:'textbox',options:{required:true}
					}},
	              {field:'remark',title:'备注',sortable:true,editor:{
						type:'textbox'
					}},
	              {field:'creator_name',title:'创建人',sortable:true},
	              {field:'create_time',title:'创建日期',sortable:true}
	          ]];
	
	//
	var gridOptions={
		idField:'id',//指定id字段
	    singleSelect: true,//单选
		rownumbers:true,//显示序号
		columns:columns,//定义显示列
		onSortColumn:onSortColumn,//点击排序按钮触发函数
		onDblClickRow:function (rowIndex,rowData){
			dg.datagrid('beginEditing',rowData);
		},//双击行触发函数
		//selectOnCheck:false,//点击复选框是否选中该行
		//checkOnSelect:false,//点击行时是否选中复选框
		multiSort:true//是否启用多列排序
	};
	var paginationOptions={layout:['list','sep','first','prev','sep','manual','sep','next','last','sep','refresh'],
			pageSize:15,
			pageList:[15,30,50],
		    onSelectPage: onSelectPage
	}
	var gridParam={"pageNumber":"1","pageSize":paginationOptions.pageSize};
	var sessionuser;//登录用户信息
	//document ready
	$(function(){
		
		dg=$('#gridList');
		$('#addButton').bind('click', addRow);//新增行绑定事件
		$('#saveButton').bind('click', accept);//保存datagrid绑定事件
		$('#cancelEditButton').bind('click', function(){dg.datagrid('cancelEditing');});//取消行编辑绑定事件
		$('#endEditingButton').bind('click', function(){dg.datagrid('endEditing');});//结束行编辑绑定事件
		$('#rejectButton').bind('click', function(){dg.datagrid('rejectChanges');});//撤销编辑绑定事件		
		$('#authButton').bind('click', menuAuth);//菜单权限设置绑定事件
	    $('#removeButton').bind('click', function(){dg.datagrid('remove');});//删除行绑定事件
	    $('#searchButton').bind('click', loadData);//查询操作绑定事件
	    $('#editButton').bind('click',editRow);//编辑按钮绑定事件
	    //$('#formSaveButton').bind('click', formSaveButton);
	    //$('#formCancelButton').bind('click', formCancelButton);
	    
	    gridOptions.toolbar="#searchbar";//搜索框绑定到datagrid
	    //初始化datagrid数据
	    $.ajax({
			type: "post",
			contentType:"application/json",
			url: "/authenticated/grid/grid_"+moduleid,
			data:JSON.stringify(gridParam),
			dataType:"json",
			success: function(rsp){
				gridOptions.data=rsp.rows;
				dg.datagrid(gridOptions);
				paginationOptions.total=rsp.total;
				$('#pager').pagination(paginationOptions);
			},
			error: function(){
				alert("error");
			}
		});
	    
	    //初始化搜索框
	    
	    //取登录用户信息
	    $.ajax({
			type: "post",
			contentType:"application/json",
			url: "/authenticated/user/sessionuser",
			dataType:"json",
			success: function(result){
				if(result.success){
					sessionuser=result.data;
				}	
			},
			error: function(){
				alert("error");
			}
		});
	});
    
	
	/*$('#gridList').datagrid(gridOptions);
	$('#pager').pagination({layout:['list','sep','first','prev','sep','manual','sep','next','last','sep'],
		total:10,
		pageSize:1,
		pageList: [1,2,3],
	    onSelectPage: function(pageNumber, pageSize){
	        alert(pageNumber+","+pageSize);
	    }
		});*/
	/*$.ajaxSetup({
		contentType:"application/json"
	});*/
	
	/**
	 * 当点击排序的时候触发
	 * sort：排序的列的字段名
	   order：排序的列的顺序
	 */
	function onSortColumn(sort, order){
		gridParam.sort=sort;
		gridParam.order=order;
		//alert(sort+","+order);
		loadData();
	}
	/**
	 * 当翻页时触发
	 */
	function onSelectPage(pageNumber, pageSize){
		gridParam.pageNumber=pageNumber;
		gridParam.pageSize=pageSize;
    	loadData();
	}
	//点击保存按钮
	function accept(){
		if (dg.datagrid('endEditing')){
			var rows = dg.datagrid('getChanges');
			if (rows.length == 0) {
				$.messager.alert("提示", "没有需要提交的数据！");
				return;
			}
			var insertedRows = dg.datagrid('getChanges','inserted');
			var deletedRows  = dg.datagrid('getChanges','deleted');
			var updatedRows  = dg.datagrid('getChanges','updated');
			var params = {};
			if(insertedRows.length>0){
				params.insertedRows=insertedRows;
			}
			if(updatedRows.length>0){
				params.updatedRows=updatedRows;
			}
			if(deletedRows.length>0){
				var idArr=new Array();
				var idField=dg.datagrid('options').idField;
				console.log(idField);
				$.each(deletedRows, function(i, row){
					idArr.push(row[idField]);
				});
				params.deletedRowIds=idArr;
			}
			$.ajax({
				type: "post",
				contentType:"application/json",
				url: "/authenticated/grid/update/grid_"+moduleid,
				data:JSON.stringify(params),
				dataType:"json",
				success: function(result){
					if(result.success){
						dg.datagrid('acceptChanges');
						loadData();
						$.messager.alert("提示", "保存成功！");
					}else{
						$.messager.alert("错误", result.message);
					}			
				},
				error: function(){
					$.messager.alert("提示", "请求失败！");
				}
			});
		}
	}
	/**
	 * 双击事件
	 */
	function onDblClickRow(rowIndex,rowData){
		dg.datagrid('beginEditing',rowData);
	}
	/**
	 * 新增一行
	 */
    function addRow(){
    	var newRowData={id:guid(),creator_id:sessionuser.id,creator_name:sessionuser.nickname,create_time:moment().format('YYYY-MM-DD')};//初始化行数据
    	console.log("新增一行："+newRowData);
    	dg.datagrid('append',newRowData);
    	
    }
    //查询
	function loadData(){
		dg.datagrid("loading");
		var searchParam=$("#searchForm").serializeObject();
		$.extend(searchParam,gridParam);
		$.ajax({
			type: "post",
			contentType:"application/json",
			url: "/authenticated/grid/grid_"+moduleid,
			data:JSON.stringify(searchParam),
			dataType:"json",
			success: function(rsp){
				$('#gridList').datagrid("loadData",rsp.rows);
				$('#gridList').datagrid("loaded");
			},
			error: function(){
				$.messager.alert("提示", "请求失败！");
			}
		});
	}
	/**
	 * 查看改变内容
	 */
	function getChanges(){
		if (dg.datagrid('endEditing')){
			//dg.datagrid('cancelEdit', dg.data("editIndex"));
			//dg.removeData('editIndex');
			var changesRows=dg.datagrid('getChanges');
			var insertedRows = dg.datagrid('getChanges','inserted');
			var deletedRows = dg.datagrid('getChanges','deleted');
			var updatedRows = dg.datagrid('getChanges','updated');
			$.messager.alert("提示", changesRows.length+"条数据修改<br>新增"+insertedRows.length+"条,删除"+deletedRows.length+"条，更新"+updatedRows.length+"条");
		}else{
			$.messager.alert("提示", "编辑未结束！");
		}
		
	}
	function formCancelButton(){
		$('#formCancelButton').dialog('close')
	}
	/**
	 * 
	 */
    function openFormDialog(){
    	$('#formDialog').dialog('open').dialog('setTitle','新增用户');
    	$('#myForm').form('clear');
    }
    function menuAuth(){
    	var selectRows=dg.datagrid('getSelections');
		if(selectRows.length>0){
			selectRowid=selectRows[0].id;
			initmenu(selectRowid);
		}else{
			$.messager.alert("提示", "请选择一条数据！");
		}
    }
    /**
     * 菜单授权查询
     */
    function initmenu(roleid){
    	$.ajax({
    		type: "post",
    		contentType:"application/json",
    		async:false,
    		url: "/authenticated/ajax/select_role_auth_menu",
    		data:JSON.stringify({role_id:roleid}),
    		dataType:"json",
    		success: function(result){
    			if(result.success){
    				$('#funcTreePanel').dialog('open');
    				zNodes=result.data;
    				zNodes.push(menuRoot);
    				zTreeMenu=$.fn.zTree.init($("#menuTree"), ztreeSeting,zNodes);
    				zTreeMenu.expandAll(true);
    			}
    		},
    		error: function(){
    			
    		}
    	});
    }
    function closePanel(){
		$('#funcTreePanel').dialog('close');
	}
    /**
     * 保存菜单权限
     */
    function saveFuncSet(){
    	var nodes = zTreeMenu.getCheckedNodes(true);
    	var checkArray=new Array();
    	$.each(nodes,function(i,v){
    		checkArray.push(v.id);
		});
    	var param={"roleid":selectRowid,"menuids":checkArray};
    	$.ajax({
    		type: "post",
    		contentType:"application/json",
    		async:false,
    		url: "/authenticated/rolemenu",
    		data:JSON.stringify(param),
    		dataType:"json",
    		success: function(result){
    			if(result.success){
    				$.messager.alert("提示", "授权成功！");
    				closePanel();
    			}else{
    				$.messager.alert("提示", "授权失败！<br>"+result.message);
    			}
    		},
    		error: function(){
    			$.messager.alert("提示", "请求失败！");
    		}
    	});
    	
    	selectRowid=undefined;
    }
    /**
     * 编辑一行
     */
    function editRow(){
    	var selectRows=dg.datagrid('getSelections');
		if(selectRows.length>0){
			dg.datagrid('beginEditing',selectRows[0]);
		}else{
			$.messager.alert("提示", "请选择一条数据！");
		}
    }